package com.appspot.urlheap.servlets;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.urlheap.data.Item;
import com.appspot.urlheap.data.PMF;
import com.google.appengine.api.datastore.Link;
import com.google.appengine.api.datastore.Text;

public class AddServlet extends BaseServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		super.doGet(req, resp);
		
		String pUrl = req.getParameter("url");
		if (pUrl == null) {
			resp.setContentType("text/html");
			resp.getWriter().println("error: missing url param");
			return;
		}
		Link url = new Link(pUrl);

		String pTitle = req.getParameter("title");
		String title = (pTitle != null && pTitle.length() > 0) ? pTitle : "unknown";

		Text desc = new Text("");
		Item item = new Item(url, title, desc, getUser().getEmail());

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(item);
		} finally {
			pm.close();
		}
		String pPrevUrl = req.getParameter("prev");
		System.out.println(pPrevUrl);
		resp.sendRedirect(pUrl);
	}
}
